package com.wingsfrog.Amap;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Amap extends CordovaPlugin {
    private static AMapLocationClient mLocationClient = null;
    private static AMapLocationListener mLocationListener = null;
    private CallbackContext callbackContext = null;

    @Override
    protected void pluginInitialize() {
        super.pluginInitialize();
        mLocationClient = new AMapLocationClient(cordova.getActivity().getApplicationContext());
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation == null) return;
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    try {
                        JSONObject result = new JSONObject();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(amapLocation.getTime());

                        //result.put("type", amapLocation.getLocationType());
                        //result.put("accuracy", amapLocation.getAccuracy());
                        //result.put("date", df.format(date));
                        result.put("latitude", amapLocation.getLatitude());
                        result.put("longitude", amapLocation.getLongitude());
                        result.put("address", amapLocation.getAddress());
                        //result.put("country", amapLocation.getCountry());
                        result.put("province", amapLocation.getProvince());
                        result.put("city", amapLocation.getCity());
                        result.put("district", amapLocation.getDistrict());
                        result.put("cityCode", amapLocation.getCityCode());
                        result.put("adCode", amapLocation.getAdCode());
                        callbackContext.success(result);
                    } catch (JSONException e) {
                        callbackContext.error(e.getMessage());
                    } finally {
                        mLocationClient.stopLocation();
                    }
                } else {
                    callbackContext.error(amapLocation.getErrorInfo());
                }
            }
        };
        mLocationClient.setLocationListener(mLocationListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
    }

    @Override
    public boolean execute(String action, final JSONArray args, final CallbackContext context) {
        if ("getLocation".equals(action)) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    getLocation(args, context);
                }
            });
        } else
            return false;
        return true;
    }

    public void getLocation(final JSONArray args, final CallbackContext context) {
        this.callbackContext = context;

        AMapLocationClientOption mLocationOption = null;
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
}
